package com.ysc.mysearch3

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.ProgressBar
import android.widget.Spinner
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import org.mozilla.gecko.util.ThreadUtils
import org.mozilla.geckoview.GeckoRuntime
import org.mozilla.geckoview.GeckoRuntimeSettings
import org.mozilla.geckoview.GeckoSession
import org.mozilla.geckoview.GeckoView
import org.mozilla.geckoview.WebExtension

class MainActivity : AppCompatActivity() {

    private lateinit var geckoView: GeckoView
    private lateinit var session: GeckoSession
    private var sRuntime: GeckoRuntime? = null

    private var txtSearch: EditText? = null
    private var progressBar: ProgressBar? = null
    private var btnSearch: Button? = null

    private var mPort: WebExtension.Port? = null
    private var webExtension: WebExtension? = null

    private lateinit var searchUrl: String

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }


        txtSearch = findViewById<EditText>(R.id.etSearch)
        progressBar = findViewById<ProgressBar>(R.id.progressBar)
        btnSearch = findViewById<Button>(R.id.btnSearch)

        // 配置 Spinner 下拉选项
        val spinner = findViewById<Spinner>(R.id.spinnerSites)
        val sites = listOf("今日头条","必应") // 可选项
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, sites)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinner.adapter = adapter

        // 处理 Spinner 选择事件
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                val selectedSite = sites[position]
                //Toast.makeText(this@MainActivity, "已选择: $selectedSite", Toast.LENGTH_SHORT).show()
                when(position){
                    0->searchUrl = "https://so.toutiao.com/search?dvpf=mobile&source=sug&keyword="
                    1->searchUrl = "https://cn.bing.com/search?q="
                }
            }
            override fun onNothingSelected(parent: AdapterView<*>?) {
                // 未选择时的处理（可选）
            }
        }


        session = GeckoSession()
        if (sRuntime == null) {
            val settings =
                GeckoRuntimeSettings.Builder().remoteDebuggingEnabled(true).build()
            sRuntime = GeckoRuntime.create(this, settings)
        }


        val portDelegate: WebExtension.PortDelegate =
            object : WebExtension.PortDelegate {
                override fun onPortMessage(
                    message: Any, port: WebExtension.Port
                ) {
                    Log.d("PortDelegate", "aaaaReceived message from extension: $message")
                }
                override fun onDisconnect(port: WebExtension.Port) {
                    // This port is not usable anymore.
                    if (port === mPort) {
                        mPort = null
                    }
                }
            }
        val messageDelegate: WebExtension.MessageDelegate =
            object : WebExtension.MessageDelegate {
                override fun onConnect(port: WebExtension.Port) {
                    Log.d("MessageDelegate", "Extension connected! Port: $port")
                    mPort = port
                    mPort!!.setDelegate(portDelegate)
                }
            }
        sRuntime!!
            .webExtensionController
            .ensureBuiltIn("resource://android/assets/messaging/", "messaging@ysc.com")
            .accept( // Register message delegate for background script
                { extension: WebExtension? ->
                    ThreadUtils.runOnUiThread {
                        extension!!.setMessageDelegate(
                            messageDelegate,
                            "browser"
                        )
                    }
                    Log.i("MessageDelegate", "Extension installed: " + extension);
//                    runOnUiThread {
//                        extension!!.setMessageDelegate(messageDelegate, "browser")
//                    }
                },
                { e: Throwable? ->
                    Log.e("MessageDelegate","Error registering WebExtension", e)
                })

        geckoView = findViewById<GeckoView>(R.id.geckoview)
        session.open(sRuntime!!)
        geckoView.setSession(session)
        session.settings.allowJavascript = true;
        session.getPanZoomController().setIsLongpressEnabled(false);

        val toutiaoUrl ="https://so.toutiao.com/search?dvpf=mobile&source=sug&keyword=wonderful"
        //session.loadUri(toutiaoUrl)
        setupSearch()
    }



    private fun setupSearch() {
        btnSearch?.setOnClickListener {
            val keyword = txtSearch?.text.toString().trim()
            if (keyword.isNotEmpty()) {
                searchStart(keyword)
            } else {
                Toast.makeText(this, "请输入搜索关键词", Toast.LENGTH_SHORT).show()
            }
        }

        // 支持键盘搜索键
        txtSearch?.setOnEditorActionListener { _, _, _ ->
            val keyword = txtSearch?.text.toString().trim()
            if (keyword.isNotEmpty()) {
                searchStart(keyword)
                true
            } else {
                false
            }
        }
    }
    private fun searchStart(keyword: String) {
        val encodedKeyword = java.net.URLEncoder.encode(keyword, "UTF-8")
        //val toutiaoUrl ="https://so.toutiao.com/search?dvpf=mobile&source=sug&keyword=wonderful"
        //val url = "https://so.toutiao.com/search?dvpf=mobile&source=sug&keyword=$encodedKeyword"
        val url = searchUrl + encodedKeyword
        session.loadUri(url)
    }


}